import React, { useState, useEffect } from 'react';
import {
  Table, Button, Space, Modal, Form, Input, Select, Switch, message,
  Card, Row, Col, Typography, Tag, Popconfirm, Drawer, Avatar,
  Upload, Tabs, Badge, Tooltip, DatePicker, Divider, Checkbox
} from 'antd';
import {
  PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined,
  UserOutlined, LockOutlined, UnlockOutlined, ReloadOutlined,
  SearchOutlined, FilterOutlined, ExportOutlined, ImportOutlined,
  MailOutlined, PhoneOutlined, TeamOutlined, KeyOutlined,
  SettingOutlined, HistoryOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import {
  userService,
  User,
  UserSearchParams,
  CreateUserRequest,
  UpdateUserRequest,
  UserStats,
  UserActivity
} from '@/services/userService';

const { Title, Text } = Typography;
const { Search } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TabPane } = Tabs;

interface UserManagementState {
  users: User[];
  loading: boolean;
  selectedUsers: string[];
  editingUser: User | null;
  viewingUser: User | null;
  modalVisible: boolean;
  detailVisible: boolean;
  searchParams: UserSearchParams;
  stats: UserStats | null;
  pagination: {
    current: number;
    pageSize: number;
    total: number;
  };
}

export default function UserManagement() {
  const [state, setState] = useState<UserManagementState>({
    users: [],
    loading: false,
    selectedUsers: [],
    editingUser: null,
    viewingUser: null,
    modalVisible: false,
    detailVisible: false,
    searchParams: {},
    stats: null,
    pagination: {
      current: 1,
      pageSize: 20,
      total: 0
    }
  });

  const [form] = Form.useForm();
  const [showFilters, setShowFilters] = useState(false);
  const [userActivities, setUserActivities] = useState<UserActivity[]>([]);
  const [activitiesLoading, setActivitiesLoading] = useState(false);

  // 加载用户列表
  const loadUsers = async (params?: Partial<UserSearchParams>) => {
    setState(prev => ({ ...prev, loading: true }));
    
    try {
      const searchParams = {
        ...state.searchParams,
        ...params,
        page: state.pagination.current - 1,
        size: state.pagination.pageSize
      };

      const response = await userService.getUsers(searchParams);
      
      setState(prev => ({
        ...prev,
        users: response.content,
        pagination: {
          ...prev.pagination,
          total: response.totalElements
        },
        loading: false
      }));
    } catch (error: any) {
      console.error('加载用户列表失败:', error);
      message.error('加载用户列表失败');
      setState(prev => ({ ...prev, loading: false }));
    }
  };

  // 加载统计数据
  const loadStats = async () => {
    try {
      const stats = await userService.getUserStats();
      setState(prev => ({ ...prev, stats }));
    } catch (error: any) {
      console.error('加载统计数据失败:', error);
    }
  };

  // 初始化
  useEffect(() => {
    loadUsers();
    loadStats();
  }, []);

  // 分页变化时重新加载
  useEffect(() => {
    loadUsers();
  }, [state.pagination.current, state.pagination.pageSize]);

  // 创建/编辑用户
  const handleSaveUser = async (values: any) => {
    try {
      if (state.editingUser) {
        await userService.updateUser(state.editingUser.id, values);
        message.success('用户更新成功');
      } else {
        await userService.createUser(values);
        message.success('用户创建成功');
      }

      setState(prev => ({
        ...prev,
        modalVisible: false,
        editingUser: null
      }));
      form.resetFields();
      loadUsers();
      loadStats();
    } catch (error: any) {
      console.error('保存用户失败:', error);
      message.error('保存用户失败');
    }
  };

  // 删除用户
  const handleDeleteUser = async (id: string) => {
    try {
      await userService.deleteUser(id);
      message.success('用户删除成功');
      loadUsers();
      loadStats();
    } catch (error: any) {
      console.error('删除用户失败:', error);
      message.error('删除用户失败');
    }
  };

  // 批量删除用户
  const handleBatchDelete = async () => {
    if (state.selectedUsers.length === 0) {
      message.warning('请先选择用户');
      return;
    }

    try {
      await userService.deleteUsers(state.selectedUsers);
      message.success('批量删除成功');
      setState(prev => ({ ...prev, selectedUsers: [] }));
      loadUsers();
      loadStats();
    } catch (error: any) {
      console.error('批量删除失败:', error);
      message.error('批量删除失败');
    }
  };

  // 更新用户状态
  const handleUpdateStatus = async (id: string, status: User['status']) => {
    try {
      await userService.updateUserStatus(id, status);
      message.success('状态更新成功');
      loadUsers();
    } catch (error: any) {
      console.error('状态更新失败:', error);
      message.error('状态更新失败');
    }
  };

  // 重置密码
  const handleResetPassword = async (userId: string) => {
    try {
      const result = await userService.resetPassword({
        userId,
        mustChangePassword: true,
        sendNotification: true
      });
      
      if (result.temporaryPassword) {
        Modal.info({
          title: '密码重置成功',
          content: (
            <div>
              <p>临时密码：<strong>{result.temporaryPassword}</strong></p>
              <p>用户下次登录时需要修改密码</p>
            </div>
          )
        });
      } else {
        message.success('密码重置邮件已发送');
      }
    } catch (error: any) {
      console.error('重置密码失败:', error);
      message.error('重置密码失败');
    }
  };

  // 查看用户详情
  const handleViewUser = async (user: User) => {
    setState(prev => ({
      ...prev,
      viewingUser: user,
      detailVisible: true
    }));

    // 加载用户活动日志
    setActivitiesLoading(true);
    try {
      const response = await userService.getUserActivities(user.id, {
        page: 0,
        size: 10
      });
      setUserActivities(response.content);
    } catch (error: any) {
      console.error('加载用户活动失败:', error);
    } finally {
      setActivitiesLoading(false);
    }
  };

  // 搜索和筛选
  const handleSearch = (params: Partial<UserSearchParams>) => {
    setState(prev => ({
      ...prev,
      searchParams: { ...prev.searchParams, ...params },
      pagination: { ...prev.pagination, current: 1 }
    }));
    loadUsers(params);
  };

  // 导出用户
  const handleExport = async () => {
    try {
      const blob = await userService.exportUsers({
        format: 'excel',
        filters: state.searchParams
      });
      
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `users-${new Date().toISOString().split('T')[0]}.xlsx`;
      link.click();
      window.URL.revokeObjectURL(url);
      
      message.success('导出成功');
    } catch (error: any) {
      console.error('导出失败:', error);
      message.error('导出失败');
    }
  };

  // 获取状态颜色
  const getStatusColor = (status: User['status']) => {
    switch (status) {
      case 'active': return 'green';
      case 'inactive': return 'default';
      case 'locked': return 'red';
      case 'pending': return 'orange';
      default: return 'default';
    }
  };

  // 获取状态文本
  const getStatusText = (status: User['status']) => {
    switch (status) {
      case 'active': return '正常';
      case 'inactive': return '禁用';
      case 'locked': return '锁定';
      case 'pending': return '待激活';
      default: return '未知';
    }
  };

  // 表格列定义
  const columns: ColumnsType<User> = [
    {
      title: '用户',
      key: 'user',
      render: (_, record: User) => (
        <Space>
          <Avatar 
            src={record.avatar} 
            icon={<UserOutlined />}
            size="small"
          />
          <div>
            <div>{record.displayName}</div>
            <Text type="secondary" style={{ fontSize: '12px' }}>
              @{record.username}
            </Text>
          </div>
        </Space>
      )
    },
    {
      title: '联系方式',
      key: 'contact',
      render: (_, record: User) => (
        <div>
          <div>
            <MailOutlined style={{ marginRight: 4 }} />
            {record.email}
            {record.emailVerified && (
              <Tag color="green" style={{ marginLeft: 4 }}>已验证</Tag>
            )}
          </div>
          {record.phone && (
            <div style={{ marginTop: 2 }}>
              <PhoneOutlined style={{ marginRight: 4 }} />
              {record.phone}
              {record.phoneVerified && (
                <Tag color="green" style={{ marginLeft: 4 }}>已验证</Tag>
              )}
            </div>
          )}
        </div>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: User['status']) => (
        <Tag color={getStatusColor(status)}>
          {getStatusText(status)}
        </Tag>
      )
    },
    {
      title: '角色',
      dataIndex: 'roles',
      key: 'roles',
      render: (roles: User['roles']) => (
        <Space wrap>
          {roles.slice(0, 2).map(role => (
            <Tag key={role.id} color="blue">{role.name}</Tag>
          ))}
          {roles.length > 2 && (
            <Tag>+{roles.length - 2}</Tag>
          )}
        </Space>
      )
    },
    {
      title: '部门',
      dataIndex: 'departments',
      key: 'departments',
      render: (departments: User['departments']) => (
        <Space wrap>
          {departments.slice(0, 1).map(dept => (
            <Tag key={dept.id} color="purple">
              {dept.name}
              {dept.isManager && <TeamOutlined style={{ marginLeft: 2 }} />}
            </Tag>
          ))}
          {departments.length > 1 && (
            <Tag>+{departments.length - 1}</Tag>
          )}
        </Space>
      )
    },
    {
      title: '最后登录',
      dataIndex: 'lastLoginAt',
      key: 'lastLoginAt',
      render: (date: string) => date ? new Date(date).toLocaleString() : '-'
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date: string) => new Date(date).toLocaleDateString()
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record: User) => (
        <Space>
          <Tooltip title="查看详情">
            <Button
              type="text"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleViewUser(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="text"
              size="small"
              icon={<EditOutlined />}
              onClick={() => {
                setState(prev => ({
                  ...prev,
                  editingUser: record,
                  modalVisible: true
                }));
                form.setFieldsValue(record);
              }}
            />
          </Tooltip>
          <Tooltip title="重置密码">
            <Button
              type="text"
              size="small"
              icon={<KeyOutlined />}
              onClick={() => {
                Modal.confirm({
                  title: '确认重置密码',
                  content: `确定要重置用户 "${record.displayName}" 的密码吗？`,
                  onOk: () => handleResetPassword(record.id)
                });
              }}
            />
          </Tooltip>
          {record.status === 'locked' ? (
            <Tooltip title="解锁">
              <Button
                type="text"
                size="small"
                icon={<UnlockOutlined />}
                onClick={() => handleUpdateStatus(record.id, 'active')}
              />
            </Tooltip>
          ) : (
            <Tooltip title="锁定">
              <Button
                type="text"
                size="small"
                icon={<LockOutlined />}
                onClick={() => handleUpdateStatus(record.id, 'locked')}
              />
            </Tooltip>
          )}
          <Popconfirm
            title="确定要删除这个用户吗？"
            onConfirm={() => handleDeleteUser(record.id)}
          >
            <Tooltip title="删除">
              <Button
                type="text"
                size="small"
                icon={<DeleteOutlined />}
                danger
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div className="p-6">
      <div className="mb-6">
        <Title level={2}>用户管理</Title>
        <Text type="secondary">管理系统用户账户、角色和权限</Text>
      </div>

      {/* 统计卡片 */}
      {state.stats && (
        <Row gutter={16} className="mb-6">
          <Col span={6}>
            <Card>
              <div className="text-center">
                <div className="text-2xl font-bold text-blue-600">{state.stats.total}</div>
                <div className="text-gray-500">总用户数</div>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <div className="text-center">
                <div className="text-2xl font-bold text-green-600">{state.stats.active}</div>
                <div className="text-gray-500">活跃用户</div>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <div className="text-center">
                <div className="text-2xl font-bold text-orange-600">{state.stats.newUsers}</div>
                <div className="text-gray-500">新增用户</div>
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <div className="text-center">
                <div className="text-2xl font-bold text-purple-600">{state.stats.recentLogins}</div>
                <div className="text-gray-500">近期登录</div>
              </div>
            </Card>
          </Col>
        </Row>
      )}

      {/* 工具栏 */}
      <Card size="small" className="mb-4">
        <Row justify="space-between" align="middle">
          <Col>
            <Space>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => {
                  setState(prev => ({
                    ...prev,
                    editingUser: null,
                    modalVisible: true
                  }));
                  form.resetFields();
                }}
              >
                新建用户
              </Button>
              <Button
                icon={<ImportOutlined />}
                onClick={() => message.info('导入功能开发中...')}
              >
                导入用户
              </Button>
              <Button
                icon={<ExportOutlined />}
                onClick={handleExport}
              >
                导出用户
              </Button>
              <Button
                icon={<ReloadOutlined />}
                onClick={() => {
                  loadUsers();
                  loadStats();
                }}
              >
                刷新
              </Button>
            </Space>
          </Col>
          <Col>
            <Space>
              <Search
                placeholder="搜索用户..."
                allowClear
                style={{ width: 200 }}
                onSearch={(value) => handleSearch({ keyword: value })}
              />
              <Button
                icon={<FilterOutlined />}
                onClick={() => setShowFilters(!showFilters)}
              >
                筛选
              </Button>
            </Space>
          </Col>
        </Row>

        {/* 高级筛选 */}
        {showFilters && (
          <div className="mt-4 p-4 bg-gray-50 rounded">
            <Row gutter={16}>
              <Col span={6}>
                <Select
                  placeholder="用户状态"
                  allowClear
                  style={{ width: '100%' }}
                  onChange={(value) => handleSearch({ status: value })}
                >
                  <Option value="active">正常</Option>
                  <Option value="inactive">禁用</Option>
                  <Option value="locked">锁定</Option>
                  <Option value="pending">待激活</Option>
                </Select>
              </Col>
              <Col span={6}>
                <Select
                  placeholder="邮箱验证状态"
                  allowClear
                  style={{ width: '100%' }}
                  onChange={(value) => handleSearch({ emailVerified: value })}
                >
                  <Option value={true}>已验证</Option>
                  <Option value={false}>未验证</Option>
                </Select>
              </Col>
              <Col span={6}>
                <RangePicker
                  placeholder={['创建开始时间', '创建结束时间']}
                  style={{ width: '100%' }}
                  onChange={(dates) => {
                    if (dates) {
                      handleSearch({
                        createdRange: {
                          start: dates[0]?.toISOString() || '',
                          end: dates[1]?.toISOString() || ''
                        }
                      });
                    }
                  }}
                />
              </Col>
              <Col span={6}>
                <Button
                  block
                  onClick={() => {
                    setState(prev => ({ ...prev, searchParams: {} }));
                    loadUsers({});
                  }}
                >
                  清除筛选
                </Button>
              </Col>
            </Row>
          </div>
        )}

        {/* 批量操作 */}
        {state.selectedUsers.length > 0 && (
          <div className="mt-4 p-3 bg-blue-50 rounded">
            <Space>
              <Text>已选择 {state.selectedUsers.length} 个用户</Text>
              <Button size="small" onClick={() => message.info('批量编辑功能开发中...')}>
                批量编辑
              </Button>
              <Button size="small" onClick={() => message.info('批量分配角色功能开发中...')}>
                分配角色
              </Button>
              <Popconfirm
                title="确定要删除选中的用户吗？"
                onConfirm={handleBatchDelete}
              >
                <Button size="small" danger>
                  批量删除
                </Button>
              </Popconfirm>
            </Space>
          </div>
        )}
      </Card>

      {/* 用户列表 */}
      <Card>
        <Table
          columns={columns}
          dataSource={state.users}
          loading={state.loading}
          rowKey="id"
          rowSelection={{
            selectedRowKeys: state.selectedUsers,
            onChange: (selectedRowKeys) => {
              setState(prev => ({
                ...prev,
                selectedUsers: selectedRowKeys as string[]
              }));
            }
          }}
          pagination={{
            current: state.pagination.current,
            pageSize: state.pagination.pageSize,
            total: state.pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            onChange: (page, pageSize) => {
              setState(prev => ({
                ...prev,
                pagination: { ...prev.pagination, current: page, pageSize: pageSize || 20 }
              }));
            }
          }}
        />
      </Card>

      {/* 创建/编辑用户模态框 */}
      <Modal
        title={state.editingUser ? '编辑用户' : '新建用户'}
        open={state.modalVisible}
        onCancel={() => {
          setState(prev => ({
            ...prev,
            modalVisible: false,
            editingUser: null
          }));
          form.resetFields();
        }}
        onOk={() => form.submit()}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSaveUser}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="username"
                label="用户名"
                rules={[{ required: true, message: '请输入用户名' }]}
              >
                <Input placeholder="请输入用户名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入有效的邮箱地址' }
                ]}
              >
                <Input placeholder="请输入邮箱" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="firstName"
                label="名"
                rules={[{ required: true, message: '请输入名' }]}
              >
                <Input placeholder="请输入名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="lastName"
                label="姓"
                rules={[{ required: true, message: '请输入姓' }]}
              >
                <Input placeholder="请输入姓" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="phone"
                label="手机号"
              >
                <Input placeholder="请输入手机号" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="status"
                label="状态"
                initialValue="active"
              >
                <Select>
                  <Option value="active">正常</Option>
                  <Option value="inactive">禁用</Option>
                  <Option value="pending">待激活</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          {!state.editingUser && (
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="password"
                  label="密码"
                  rules={[{ required: true, message: '请输入密码' }]}
                >
                  <Input.Password placeholder="请输入密码" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="mustChangePassword"
                  label="强制修改密码"
                  valuePropName="checked"
                  initialValue={true}
                >
                  <Switch />
                </Form.Item>
              </Col>
            </Row>
          )}
        </Form>
      </Modal>

      {/* 用户详情抽屉 */}
      <Drawer
        title="用户详情"
        placement="right"
        width={600}
        open={state.detailVisible}
        onClose={() => setState(prev => ({ ...prev, detailVisible: false }))}
      >
        {state.viewingUser && (
          <Tabs defaultActiveKey="basic">
            <TabPane tab="基本信息" key="basic">
              <div className="space-y-4">
                <div className="text-center mb-6">
                  <Avatar 
                    src={state.viewingUser.avatar} 
                    icon={<UserOutlined />}
                    size={80}
                  />
                  <div className="mt-2">
                    <Title level={4}>{state.viewingUser.displayName}</Title>
                    <Text type="secondary">@{state.viewingUser.username}</Text>
                  </div>
                  <div className="mt-2">
                    <Tag color={getStatusColor(state.viewingUser.status)}>
                      {getStatusText(state.viewingUser.status)}
                    </Tag>
                  </div>
                </div>

                <Divider />

                <div>
                  <Text strong>联系方式</Text>
                  <div className="mt-2 space-y-2">
                    <div>
                      <MailOutlined className="mr-2" />
                      {state.viewingUser.email}
                      {state.viewingUser.emailVerified && (
                        <Badge status="success" text="已验证" className="ml-2" />
                      )}
                    </div>
                    {state.viewingUser.phone && (
                      <div>
                        <PhoneOutlined className="mr-2" />
                        {state.viewingUser.phone}
                        {state.viewingUser.phoneVerified && (
                          <Badge status="success" text="已验证" className="ml-2" />
                        )}
                      </div>
                    )}
                  </div>
                </div>

                <Divider />

                <div>
                  <Text strong>角色权限</Text>
                  <div className="mt-2">
                    <Space wrap>
                      {state.viewingUser.roles.map(role => (
                        <Tag key={role.id} color="blue">{role.name}</Tag>
                      ))}
                    </Space>
                  </div>
                </div>

                <Divider />

                <div>
                  <Text strong>所属部门</Text>
                  <div className="mt-2">
                    <Space wrap>
                      {state.viewingUser.departments.map(dept => (
                        <Tag key={dept.id} color="purple">
                          {dept.name}
                          {dept.isManager && <TeamOutlined className="ml-1" />}
                        </Tag>
                      ))}
                    </Space>
                  </div>
                </div>

                <Divider />

                <div>
                  <Text strong>登录信息</Text>
                  <div className="mt-2 space-y-1">
                    <div>最后登录：{state.viewingUser.lastLoginAt ? new Date(state.viewingUser.lastLoginAt).toLocaleString() : '从未登录'}</div>
                    <div>登录次数：{state.viewingUser.loginCount}</div>
                    <div>创建时间：{new Date(state.viewingUser.createdAt).toLocaleString()}</div>
                  </div>
                </div>
              </div>
            </TabPane>

            <TabPane tab="活动日志" key="activities">
              <div>
                {activitiesLoading ? (
                  <div className="text-center py-8">加载中...</div>
                ) : (
                  <div className="space-y-3">
                    {userActivities.map(activity => (
                      <div key={activity.id} className="border-l-2 border-blue-200 pl-4 pb-3">
                        <div className="font-medium">{activity.action}</div>
                        <div className="text-sm text-gray-600">{activity.description}</div>
                        <div className="text-xs text-gray-400 mt-1">
                          {new Date(activity.createdAt).toLocaleString()}
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </TabPane>
          </Tabs>
        )}
      </Drawer>
    </div>
  );
}